package com.leyou.filter;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.config.FilterProperties;
import com.leyou.config.JwtProperties;
import com.leyou.utils.CookieUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Description:
 * @author: Mr_Sun
 * @Date: 2018/9/25
 * @Time: 16:24
 */
@Component
@EnableConfigurationProperties({JwtProperties.class,FilterProperties.class})
public class LoginFilter extends ZuulFilter {
    @Autowired
    private JwtProperties properties;
    @Autowired
    private FilterProperties filterProperties;

    @Override
    public String filterType() {

        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {

        //获取到当前的请求路径
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        StringBuffer url = request.getRequestURL();
        List<String> allowPaths = this.filterProperties.getAllowPaths();
        for (String path : allowPaths) {
            if (StringUtils.contains(url, path)) {
                return false;
            }
        }
        return true;//是否执行run方法 true  执行  false不执行
    }

    @Override
    public Object run() throws ZuulException {
        //初始化zuul的上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        //从上下文获取request对象
        HttpServletRequest request = context.getRequest();
        //获取jwt
        String token = CookieUtils.getCookieValue(request, this.properties.getCookieName());
        try {
            //解析jwt
            JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());
            // 校验通过什么都不做，即放行
        } catch (Exception e) {
            e.printStackTrace();
            // 校验出现异常，返回403
            context.setSendZuulResponse(false);//是否让zuul网关转发请求
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
